package com.jingdianjichi.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密
 */
public class DruidEncryptUtil {

    private static String publicKey;

    private static String privateKey;

    static {
        try {
            // 生成公钥和私钥
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("privateKey = " + privateKey);
            publicKey = keyPair[1];
            System.out.println("publicKey = " + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     *
     * @param password 明文密码
     * @return 密文密码
     */
    public static String encrypt(String password) {
        try {
            return ConfigTools.encrypt(privateKey, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     *
     * @param password 密文密码
     * @return 明文密码
     */
    public static String decrypt(String password) {
        try {
            return ConfigTools.decrypt(publicKey, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String encrypt = encrypt("admin");
        String encrypt1 = encrypt("123456");
        System.out.println("encrypt = " + encrypt);
        System.out.println("encrypt1 = " + encrypt1);
    }
}
